﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EzyThirdLogic.ExtensionMethods;
using System.Collections;

namespace EzyThirdLogic
{
    public static class CoverFinding
    {
        /// <summary>
        /// method to check whether a fd is redundant in a set of fds
        /// a fd, z, is redundant for a set of fds, F, if closure of lhs attributes of z 
        /// on (F minus z) contains the attributes in rhs of z. Returns true or false
        /// </summary>
        /// <param name="fdSet"></param>
        /// <param name="fd"></param>
        /// <returns></returns>
        public static bool CheckForRedundancy(FunctionalDependencySet fdSet, FunctionalDependency fd)
        {
            FunctionalDependencySet newFDSet = new FunctionalDependencySet(fdSet);
            newFDSet.RemoveFunctionalDependency(fd);
            BitArray leftFD = (BitArray)fd.BitDeterminant.Clone();
            BitArray rightFD = (BitArray)fd.BitDependent.Clone();
            BitArray attrClosure = SynthesizingAlgorithm.AttributeClosure(newFDSet, leftFD);
            rightFD.And(attrClosure);
            if (rightFD.IsEquals(fd.BitDependent))
                return true;
            else
                return false;
        }

        /// <summary>
        /// given a set of fds, return a set where there is no redundant attributes in the set
        /// </summary>
        /// <param name="fdSet"></param>
        /// <returns></returns>
        public static FunctionalDependencySet RemoveRedundantFunctionalDependencies(FunctionalDependencySet fdSet)
        {
            FunctionalDependencySet newFDSet = new FunctionalDependencySet(fdSet);
            foreach (FunctionalDependency fd in fdSet.FDSet)
            {
                if (CheckForRedundancy(newFDSet, fd))
                    newFDSet.RemoveFunctionalDependency(fd);
            }
            return newFDSet;
        }

    }
}
